package com.sjm.bookshop.config;


import com.alibaba.fastjson.JSONObject;
import com.sjm.bookshop.utils.JwtUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//token统一拦截处理

/**
 * token验证拦截
 */
@Configuration
//@Component
@CrossOrigin
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//     在拦截器里判断是不是询问接口能不能过的，是的就放行request.getMethod().equals("OPTIONS")
        // 取得token
        String token = request.getHeader("token");
        /**HttpMethod.OPTIONS.toString().equals(request.getMethod())
         * 这里有个bug,就是请求第一次到达会出现token为空的问题，导致前端订单刷新异常
         */
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }else
            if (token != null) {
            boolean flag = JwtUtils.verify(token);
            if (flag) {
                return true;
            }

        }
        else {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            try {
                JSONObject json = new JSONObject();
                json.put("msg", "登录过期，请重新登录");
                json.put("code", "110");
                response.getWriter().append(json.toJSONString());
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
        }


        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }

}
